﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace xDataSet
{


    public class xDataSet
    {
        #region 属性
        public bool SRet
        {

            get {

                try
                {
                    if (mRetJObject["success"].ToString().ToLower() == "true")
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                catch
                {

                    return false;
                }

            }

        }

        string mRetData = "";

        /// <summary>
        /// 返回的字符串
        /// </summary>
        public string SRetData
        {
            get { return mRetData; }
            
        }

       
        string mError = "";
        /// <summary>
        /// 内部出错信息
        /// </summary>
        public string SError
        {
            get { return mError; }

        }

        string mVer = "1" ;
        public string SVer
        {
            get { return mVer;}
        }

        JObject mRetJObject = null;
        public JObject SRetJObject
        {
            get
            {
                return mRetJObject;
            }

            set
            {
                mRetJObject = value;
            }
        }

        private bool mSretSuccess = true;
        public bool SretSuccess { get { return mSretSuccess; } }

        Hashtable mPrarm = null;
        xDataSetConfigInterface mEnviroment = null;

        #endregion

        public xDataSet( string pApplication, string pMapping, string pMethod, Hashtable pPrarm, xDataSetConfigInterface pEnviroment)
        {

            f_Process(false,"1", pApplication, pMapping, pMethod, pPrarm, pEnviroment);
        }

        public  xDataSet(bool IsCache, string pApplication , string pMapping , string pMethod , Hashtable pPrarm , xDataSetConfigInterface pEnviroment)
        {
            f_Process(IsCache,"1", pApplication, pMapping, pMethod, pPrarm, pEnviroment);
        }

        public xDataSet(bool IsCache, string pVer, string pApplication, string pMapping, string pMethod, Hashtable pPrarm, xDataSetConfigInterface pEnviroment)
        {
            mVer = pVer;
            f_Process(IsCache, pVer, pApplication, pMapping, pMethod, pPrarm, pEnviroment);
        }

        public xDataSet(string pApplication, string pMapping, string pMethod, xParameter[] pPrarm, xDataSetConfigInterface pEnviroment)
        {
            Hashtable xHt = new Hashtable();
            foreach (xParameter xItem in pPrarm)
            {
                xHt.Add(xItem.Name , xItem.Data);
            }
            f_Process(false, "1", pApplication, pMapping, pMethod, xHt, pEnviroment);
        }

        public xDataSet(bool IsCache, string pApplication, string pMapping, string pMethod, xParameter[] pPrarm, xDataSetConfigInterface pEnviroment)
        {
            Hashtable xHt = new Hashtable();
            foreach (xParameter xItem in pPrarm)
            {
                xHt.Add(xItem.Name, xItem.Data);
            }
            f_Process(IsCache, "1", pApplication, pMapping, pMethod, xHt, pEnviroment);
        }

        public xDataSet(bool IsCache, string pVer, string pApplication, string pMapping, string pMethod, xParameter[] pPrarm, xDataSetConfigInterface pEnviroment)
        {
            mVer = pVer;
            Hashtable xHt = new Hashtable();
            foreach (xParameter xItem in pPrarm)
            {
                xHt.Add(xItem.Name, xItem.Data);
            }
            f_Process(IsCache, pVer, pApplication, pMapping, pMethod, xHt, pEnviroment);
        }

        void f_Process(bool IsCache,string pVer, string pApplication, string pMapping, string pMethod, Hashtable pPrarm, xDataSetConfigInterface pEnviroment)
        {
            //根据传入的参数判断是否为本地还是服务器
            mEnviroment = pEnviroment;
            mPrarm = pPrarm;


            try
            {
                Hashtable hstMain = new Hashtable();

                hstMain["token"] = mEnviroment.Token;
                hstMain["appid"] = mEnviroment.Appid;
                hstMain["verifycode"] = "";
                hstMain["devid"] = mEnviroment.DevID;
                hstMain["userid"] = mEnviroment.UserID;
                hstMain["version"] = "1.0";
                hstMain["param"] = JsonConvert.SerializeObject(pPrarm);


                string param = JsonConvert.SerializeObject(hstMain);
                mRetData = PostWebRequest(mEnviroment.RequestURL + "/" + pApplication + "/" + pMapping + "/" + pMethod,
                    param);
                //Hashtable retValue = JsonConvert.DeserializeObject<Hashtable>(mRetData);
                mRetJObject = JsonConvert.DeserializeObject(mRetData) as JObject;
            }
            catch (Exception Err)
            {
                //mRetSuccess = false;
                mError = Err.Message + "\r\n" + Err.Source + "\r\n" + Err.StackTrace;
                mSretSuccess = false;
            }

        }
        protected string PostWebRequest(string postUrl, string paramData)
        {
            string ret = string.Empty;
            try
            {
                byte[] byteArray = Encoding.UTF8.GetBytes(paramData); //转化
                HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
                webReq.Method = "POST";
                webReq.ContentType = "application/json;charset=utf8";
                webReq.ContentLength = byteArray.Length;
                Stream newStream = webReq.GetRequestStream();
                newStream.Write(byteArray, 0, byteArray.Length);//写入参数
                newStream.Close();
                HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
                StreamReader sr = null;
                if (response.StatusCode.GetHashCode().ToString() == "200")
                {
                    sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                    ret = sr.ReadToEnd();
                   
                }
                else
                {
                    mSretSuccess = false;
                    mError =string.Format("网络通讯错误！错误号http{0}",response.StatusCode.GetHashCode());
                }
                try
                {
                    sr.Close();
                    response.Close();
                    newStream.Close();
                }
                catch (Exception e)
                {
                    mSretSuccess = false;
                    mError = e.Message + "\r\n" + e.Source + "\r\n" + e.StackTrace;
                }
            }
            catch (Exception ex)
            {
                mSretSuccess = false;
                mError = ex.Message + "\r\n" + ex.Source + "\r\n" + ex.StackTrace +"\r\n"+ex.InnerException??string.Empty;
            }
            return ret;
        }
    }
}
